package cn.lj.controller;

import cn.lj.pojo.Blog;
import cn.lj.pojo.Tag;
import cn.lj.pojo.Type;
import cn.lj.service.BlogService;
import cn.lj.service.TagService;
import cn.lj.service.TypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author lj
 * @Description:
 * @date 2020-11-29 11:07
 * @QQ 851477108
 */

@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    /**
     * 博客主页，中间部分左分页查询博客，右部分列出部分类型和标签，还有推荐博客
     * @param pagenum
     * @param model
     * @return
     */
    @GetMapping("/")
    public String toIndex(@RequestParam(required = false,defaultValue = "1", value = "pagenum")int pagenum, Model model){
        PageHelper.startPage(pagenum, 8);
        List<Blog> blogs = blogService.getIndexBlog();
        //获取博客的类型(联表查询)
        List<Type> types = typeService.getBlogType();
        //获取博客的标签(联表查询)
        List<Tag> tags = tagService.getBlogTag();
        //获取推荐博客
        List<Blog> recommendBlog = blogService.getAllRecommendBlog();

        //得到分页结果对象
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("types",types);
        model.addAttribute("tags",tags);
        model.addAttribute("recommendBlogs",recommendBlog);
        return "index";
    }

    /**
     * 全局查询,右content和title
     * @param pagenum
     * @param query
     * @param model
     * @return
     */
    @PostMapping("/search")
    public String search(@RequestParam(required = false,defaultValue = "1", value = "pagenum")int pagenum,@RequestParam String query, Model model){
        PageHelper.startPage(pagenum, 5);
        List<Blog> blogs = blogService.getSearchBlog(query);

        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }

    /**
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model){
        Blog blog = blogService.getDetailedBlog(id);
        model.addAttribute("blog", blog);
        return "blog";
    }
}
